﻿using HtmlAgilityPack;
using MVBuddy.Common.Controls;
using MVBuddy.Common.Model;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media.Imaging;

namespace MVBuddy.Common.Helpers
{
    public class UserDataExtractor
    {
        public static UserData Extract(HtmlDocument document)
        {
            UserData userData = new UserData();

            HtmlNode userInfo = document.DocumentNode.Descendants().Where(child => child.Id == "userinfo").FirstOrDefault();

            if (!userInfo.InnerText.Contains("Iniciar"))
            {
                List<HtmlNode> aNodes = userInfo.ChildNodes.Where(child => child.Name == "a").ToList();

                userData.Logged = true;
                userData.Username = ExtractUsername(aNodes[0]);
                userData.NotificationCount = ExtractCountField(aNodes[1]);
                userData.FavoriteCount = ExtractCountField(aNodes[2]);
                userData.MessageCount = ExtractCountField(aNodes[3]);
            }

            return userData;
        }

        public static WriteableBitmap RenderUserDataForBackgroundTile(UserData userData)
        {
            TileBackBackgroundControl backBackground = new TileBackBackgroundControl();
            backBackground.DataContext = userData;
            backBackground.Measure(new Size(173, 173));
            backBackground.Arrange(new Rect(0, 0, 173, 173));
            
            WriteableBitmap bitmap = new WriteableBitmap(173, 173);
            bitmap.Render(backBackground, null);
            bitmap.Invalidate();

            return bitmap;
        }

        private static string ExtractUsername(HtmlNode node)
        {
            if (node.FirstChild.Name == "span")
            {
                return node.FirstChild.InnerText;
            }

            return string.Empty;
        }

        private static int ExtractCountField(HtmlNode node)
        {
            if (node.FirstChild.Name == "strong")
            {
                return int.Parse(node.FirstChild.InnerText);
            }

            return 0;
        }
    }
}
